<?php

namespace app\index\controller;

use app\model\OrderDao;
use app\service\WechatPay;
use think\admin\Controller;
use think\facade\Log;

class Wechat extends Controller
{
    public function notice()
    {
        $xml = $this->request->getContent();
        Log::debug('微信支付回调: {xml}', compact('xml'));
        $wxObj = new WechatPay();
        $data = $wxObj->FromXml($xml);
        //重组签名校验是否与本地签名一致
        $sign = $data['sign'];
        $key= config('wechat.svc_api_key');
        if ($wxObj->MakeSign($data,$key) == $sign && $data['result_code'] == 'SUCCESS') {
            $orderNo = $data['out_trade_no'];
            $order = OrderDao::where(['order_num' => $orderNo])->find();
            if (empty($order)) {
                Log::debug("{orderNo} 订单不存在", compact('orderNo'));
                return 'SUCCESS';
            }
            if ((int)$order->pay_status > 0) {
                Log::debug("{orderNo} 订单已处理", compact('orderNo'));
                return 'SUCCESS';
            }
            $time = time();
            $order->save([
                'pay_status' => 1,
                'pay_time' => date("Y-m-d H:i:s", $time),
                //'status' => 1,
                'transaction_id' => $data['transaction_id'],
            ]);
        }
        return 'SUCCESS';
    }

}